package cn.edu.nuc.creditSystem.controller.credit;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;

import cn.edu.nuc.creditSystem.bean.Msg;
import cn.edu.nuc.creditSystem.bean.credit.Loanbid;
import cn.edu.nuc.creditSystem.bean.user.User;
import cn.edu.nuc.creditSystem.controller.BaseController;
import cn.edu.nuc.creditSystem.service.BaseService;
import cn.edu.nuc.creditSystem.service.credit.service.AccountService;
import cn.edu.nuc.creditSystem.service.credit.service.LoanbidService;
import cn.edu.nuc.creditSystem.utils.AnalogInterface;
import cn.edu.nuc.creditSystem.utils.Arith;

@Controller
@RequestMapping("/cs/credit/loanbid")
public class LoanbidController extends BaseController<Loanbid>{
	@Autowired
	private LoanbidService ls; 
	@Autowired
	private AnalogInterface ai;
	@Autowired
	private AccountService as;
	@Override
	protected BaseService<Loanbid> getService() {
		return ls;
	}

	@Override
	protected String getPrefix() {
		return "/credit/loanbid/";
	}
	/**
	 * 未认证时贷款信息查看
	 * @return
	 */
	@RequestMapping("/creditSelect")
	private String creditSelect(){
		return "/credit/loanbid/look";
	}
	/**
	 * 已认证时贷款信息查看
	 * @return
	 */
	@RequestMapping("/loan")
	private String loanSelect(){
		return "/credit/loanbid/loan";
	}
	/**
	 * 债权转让
	 * @return
	 */
	@RequestMapping("/loantransfer")
	private String loantransfer(){
		return "/credit/loanbid/loantransfer";
	}
	@ResponseBody
	@RequestMapping("/totransfer")
	private Msg agreeSecurity(User user,Integer loanid,String otherUsername,HttpSession session){
		User user2=(User) session.getAttribute("user");
		if(otherUsername.equals(user2.getUsername()))return new Msg(Msg.error,"您的债权转让不能转给自己！");
		return ls.toTransferLoanbid(user,user2,loanid,otherUsername);
	}
	
	@ResponseBody
	@RequestMapping("/loanCombobox")
	private List<User> getCombobox(Double money,HttpSession session){
		User user=(User)session.getAttribute("user");
		List<User> list=ls.querySecurity(money);
		if(list==null)return null;
		for(User u:list){
			if(u.getId()==user.getId())list.remove(u);
		}
		return list;
	}
	@RequestMapping(value = "/saveLoanbid", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String save(Loanbid model,HttpSession session) throws Exception {
		User user=(User)session.getAttribute("user");
		Gson g=new Gson();
		if (model.getId() == null) {
			model.setPublisher(user.getId());
			return g.toJson(getService().insert(model));
		} else {
			return g.toJson(getService().update(model));
		}
	}
	@ResponseBody
	@RequestMapping("/agreeSecurity")
	private Msg agreeSecurity(Integer id,HttpSession session){
		try{
			User user=(User)session.getAttribute("user");
			Loanbid l=ls.get(id);
			if(as.get(user.getId()).getMoney()<l.getMoney())return new Msg(Msg.error,"您的账户资金不足，请及时充值！");
			if(user.getId()!=l.getSecurity())return new Msg(Msg.error,"账户出现错误！");
			ls.updateStatus(id.toString(),2);
			ai.transferAccount(l.getSecurity(),1,l.getMoney(),"同意贷款押金"+l.getMoney()+"元。",2);
			return new Msg(Msg.success,"审批成功！");
		}catch(Exception e){
			e.printStackTrace();
		}
		return new Msg(Msg.error,"可能由于您的资金不足或系统出现问题，请联系管理员修正！");
	}
	@ResponseBody
	@RequestMapping("/agreeCredit")
	private Msg agreeCredit(Integer id,HttpSession session){
		try{
			User user=(User)session.getAttribute("user");
			Loanbid l=ls.get(id);
			l.setState(4);
			l.setCrediter(user.getId());
			l.setCredittime(new Date());
			ls.update(l);
			if(as.get(user.getId()).getMoney()<l.getMoney())return new Msg(Msg.error,"您的账户资金不足，请及时充值！");
			ai.transferAccount(user.getId(),l.getPublisher(),l.getMoney(),"交易贷款标（"+l.getTitle()+"），转账"+l.getMoney()+"元。",3);
			return new Msg(Msg.success,"购买成功！");
		}catch(Exception e){
			e.printStackTrace();
		}
		return new Msg(Msg.error,"可能由于您的资金不足或系统出现问题，请联系管理员修正！");
	}
	@ResponseBody
	@RequestMapping("/repayment")
	private Msg repayment(Integer id,HttpSession session){
		try{
			User user=(User)session.getAttribute("user");
			Loanbid l=ls.get(id);
			if(l.getPublisher()!=user.getId())return new Msg(Msg.error,"账户信息错误！");
			Double p=Arith.mul(l.getInterest(), Arith.mul(l.getMoney(),l.getMonths()));
			if(as.get(user.getId()).getMoney()<p)return new Msg(Msg.error,"您的账户资金不足，请及时充值！");
			ai.transferAccount(1,l.getSecurity(), l.getMoney(),"返还担保资金"+l.getMoney()+"元",2);
			ai.transferAccount(user.getId(),l.getCrediter(),l.getMoney(),"交易贷款标（"+l.getTitle()+"），逾期 还款"+l.getMoney()+"元。",0);
			ai.transferAccount(user.getId(),l.getCrediter(),p,"交易贷款标（"+l.getTitle()+"），还清利息"+p+"元。",1);
			ls.updateStatus(id.toString(),6);
			return new Msg(Msg.success,"还款成功！");
		}catch(Exception e){
			e.printStackTrace();
		}
		return new Msg(Msg.error,"可能由于您的资金不足或系统出现问题，请联系管理员修正！");
	}
	@ResponseBody
	@RequestMapping("/overdue")
	private Msg overdue(Integer id,HttpSession session){
		try{
			Loanbid l=ls.get(id);
			ai.transferAccount(1,l.getCrediter(),l.getMoney(),"交易贷款标（"+l.getTitle()+"），逾期垫付还款"+l.getMoney()+"元。",0);
			ls.updateStatus(id.toString(),6);
			return new Msg(Msg.success,"逾期由担保人担保资金垫付，操作成功！");
		}catch(Exception e){
			e.printStackTrace();
		}
		return new Msg(Msg.error,"可能由于您的资金不足或系统出现问题，请联系管理员修正！");
	}
}
